/**
 * excel模板替换生成
 */
const XlsxTemplate = require('xlsx-template');
const fs = require('fs');
const path = require('path');

/**
 * 根据模板文档生成excel文档
 * @param {string} inFile 模板文档名
 * @param {object} data 要替换的数据
 * @param {string} outFile 输出文档名
 */
function generateFile (inFile, data, outFile) {
  let rootFolder = '';// 根据目录
  if (process.env.NODE_ENV === 'development') { // 开发环境
    rootFolder = path.join(path.resolve(), 'uploads');
  } else { // 生产环境
    rootFolder = path.join(path.resolve(), '../uploads');
  }
  if (!fs.existsSync(rootFolder)) {
    fs.mkdirSync(rootFolder)
  }

  const inFolder = path.join(rootFolder, 'template'); // 模板目录
  const outFolder = path.join(rootFolder, 'output'); // 输出目录
  if (!fs.existsSync(outFolder)) {
    fs.mkdirSync(outFolder)
  }

  // 读取excel文件到内存
  const content = fs.readFileSync(path.join(inFolder, inFile));
  // 创建模板
  const template = new XlsxTemplate(content);
  // 内容替换发生在第一个sheet
  const sheetNumber = 1;

  // 执行替换
  template.substitute(sheetNumber, data);
  // 获取二进制数据
  const buf = template.generate({ type: 'nodebuffer' });
  fs.writeFileSync(path.join(outFolder, outFile), buf);

  return {
    url: path.join('/uploads/output', outFile),
    file: outFile
  };
}

exports.generateFile = generateFile;
